﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SureKAM.BackUp.Notify.Presenter;
using SureKAM.BackUp.Notify.Presenter.Interfaces;
using SureKAM.BackUp.Notify.Presenter.ViewInterfaces;
using SureKAM.BackUp.Notify.Service;
using System.Threading;
using Timer = System.Threading.Timer;

namespace SureKAM.BackUp.Notify.WinForm
{
    public partial class ConfigParameter : Form, IConfigParameterView
    {
        private IConfigParameterPresenter configParameterPresenter;
        private bool Flags = false;
        private System.Threading.Timer timerReflush;
        private System.Threading.Timer mailReflush;
        public ConfigParameter()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 绑定DataDirectory对象
        /// </summary>
        /// <param name="directories"></param>
        public void DatabindDirectory(List<SureKAM.BackUp.Notify.Domain.Directory> directories)
        {
            if (directories != null)
            {
                this.dataDriectory.DataSource = null;
                this.dataDriectory.DataSource = directories;
            }
        }

        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConfigParameter_Load(object sender, EventArgs e)
        {
            this.dataDriectory.AutoGenerateColumns = false;
            this.notifys.DisplayMember = "Name";
            this.configParameterPresenter = new ConfigParameterPresenter(this, new DirectoryService(), new NotifyService());
            load();
        }

        /// <summary>
        /// 加载
        /// </summary>
        protected void load()
        {
            this.configParameterPresenter.Init();
            if (this.dataDriectory.Rows.Count > 0)
            {
                this.dataDriectory.Rows[0].Selected = true;
                string currentId = this.dataDriectory.Rows[this.dataDriectory.CurrentCell.RowIndex].Cells[0].Value.ToString();
                this.SelectNotify(currentId);
            }
        }

        /// <summary>
        /// 更新日志
        /// </summary>
        /// <param name="obj"></param>
        private void TimerCall(object obj)
        {
            this.logList.Items.Clear();
            List<string> strings = getLog();
            if (strings != null)
            {
                for (int i = strings.Count - 1; i >= 0; i--)
                {
                    this.logList.Items.Add(strings[i]);
                }
            }
            timerReflush = new Timer(new TimerCallback(TimerCall), null, 5000, 0);
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="obj"></param>
        private void MailCall(object obj)
        {
            if (this.Flags)
            {
                ////发送邮件
                mailSend();
            }
            else
            {
                this.Flags = true;
            }
            mailReflush = new Timer(new TimerCallback(MailCall), null, 3600000 * 24, 0);
        }

        /// <summary>
        /// 绑定Notify
        /// </summary>
        /// <param name="notifies"></param>
        public void DataBindNotifys(List<Domain.Notify> notifies)
        {
            this.notifys.Items.Clear();
            if (notifies != null)
            {
                foreach (Domain.Notify notify in notifies)
                {
                    this.notifys.Items.Add(notify);
                }
            }
        }

        /// <summary>
        /// 改选DataGridView先，加相应的Notify选中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataDriectory_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                string currentId = this.dataDriectory.Rows[this.dataDriectory.CurrentCell.RowIndex].Cells[0].Value.ToString();
                this.SelectNotify(currentId);
            }
            catch (Exception)
            {
                this.load();
            }

        }

        /// <summary>
        /// 选中Notify
        /// </summary>
        /// <param name="currentId"></param>
        protected void SelectNotify(string currentId)
        {
            if (!string.IsNullOrEmpty(currentId))
            {
                List<Domain.Notify> notifies = this.changeSelectDirectory(currentId);
                for (int i = 0; i < this.notifys.Items.Count; i++)
                {
                    Domain.Notify notify = (Domain.Notify)this.notifys.Items[i];
                    if (notifies != null)
                    {
                        var result = from notify1 in notifies where notify1.ID == notify.ID select notify1;
                        if (result != null && result.Count() > 0) this.notifys.SetItemChecked(i, true);
                        else this.notifys.SetItemChecked(i, false);
                    }
                    else
                    {
                        this.notifys.SetItemChecked(i, false);
                    }
                }
            }
        }

        /// <summary>
        /// 修改选中节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void save_Click(object sender, EventArgs e)
        {
            List<Domain.Notify> notifies = new List<Domain.Notify>();
            string currentId = this.dataDriectory.Rows[this.dataDriectory.CurrentCell.RowIndex].Cells[0].Value.ToString();
            foreach (var checkedItem in this.notifys.CheckedItems)
            {
                Domain.Notify notify = (Domain.Notify)checkedItem;
                notifies.Add(notify);
            }
            if (!string.IsNullOrEmpty(currentId))
            {
                updateDNMapping(currentId, notifies);
            }
            MessageBox.Show("信息保存完毕!");
        }

        /// <summary>
        /// 目录管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 添加目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DirectoryWin directoryWin = new DirectoryWin();
            var m = directoryWin.ShowDialog();
            if (m == DialogResult.Cancel)
            {
                this.load();
            }
        }

        /// <summary>
        /// 通知者管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 添加通知者ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NotifyWin notifyWin = new NotifyWin();
            var m = notifyWin.ShowDialog();
            if (m == DialogResult.Cancel)
            {
                this.load();
            }
        }

        /// <summary>
        /// 启动监控
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void start_Click(object sender, EventArgs e)
        {
            this.ldateTime.Text = "监控中";
            timerReflush = new Timer(new TimerCallback(TimerCall), null, 1000, 0);
            mailReflush = new Timer(new TimerCallback(MailCall), null, 1000, 0);
            ////开始启动监控
            monitoring();
        }

        /// <summary>
        /// 监控暂停
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pluse_Click(object sender, EventArgs e)
        {
            this.ldateTime.Text = "已暂停";
            stopMonitoring();

            ////暂停邮件监控
            try
            {
                this.mailReflush.Dispose();
            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// 最小化到托盘
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConfigParameter_SizeChanged(object sender, EventArgs e)
        {
            if(this.WindowState==FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
                this.notifyIcon1.Visible = true;
            }
        }

        /// <summary>
        /// 显示最窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            if(this.WindowState==FormWindowState.Minimized)
            {
                this.ShowInTaskbar = true;
                this.WindowState = FormWindowState.Normal;
                notifyIcon1.Visible = false;
            }
        }

        public ChangeSelectDirectory changeSelectDirectory { get; set; }
        public UpdateDNMapping updateDNMapping { get; set; }
        public Monitoring monitoring { get; set; }
        public Monitoring stopMonitoring { get; set; }
        public GetLog getLog { get; set; }
        public MailSend mailSend { get; set; }
 
    }
}
